package repositories

import (
	"blog-backend/internal/app/models"
	"blog-backend/pkg/database"
)

type CommentRepository struct{}

func NewCommentRepository() *CommentRepository {
	return &CommentRepository{}
}

// Create 创建评论
func (r *CommentRepository) Create(comment *models.Comment) error {
	return database.DB.Create(comment).Error
}

// Update 更新评论
func (r *CommentRepository) Update(comment *models.Comment) error {
	return database.DB.Save(comment).Error
}

// Delete 删除评论
func (r *CommentRepository) Delete(id uint) error {
	return database.DB.Delete(&models.Comment{}, id).Error
}

// GetByID 通过ID获取评论
func (r *CommentRepository) GetByID(id uint) (*models.Comment, error) {
	var comment models.Comment
	result := database.DB.First(&comment, id)
	if result.Error != nil {
		return nil, result.Error
	}
	return &comment, nil
}

// GetByPostID 获取文章下的评论
func (r *CommentRepository) GetByPostID(postID uint) ([]models.Comment, error) {
	var comments []models.Comment
	result := database.DB.Preload("User").
		Where("post_id = ? AND parent_id IS NULL AND status = 1", postID).
		Order("created_at DESC").
		Find(&comments)
	
	if result.Error != nil {
		return nil, result.Error
	}
	
	// 加载回复评论
	for i := range comments {
		if err := r.loadReplies(&comments[i]); err != nil {
			return nil, err
		}
	}
	
	return comments, nil
}

// loadReplies 加载评论的回复
func (r *CommentRepository) loadReplies(comment *models.Comment) error {
	var replies []models.Comment
	result := database.DB.Preload("User").
		Where("parent_id = ? AND status = 1", comment.ID).
		Order("created_at ASC").
		Find(&replies)
	
	if result.Error != nil {
		return result.Error
	}
	
	// 递归加载嵌套回复
	for i := range replies {
		if err := r.loadReplies(&replies[i]); err != nil {
			return err
		}
	}
	
	comment.Replies = replies
	return nil
}

// GetPendingComments 获取待审核评论
func (r *CommentRepository) GetPendingComments(page, limit int) ([]models.Comment, int64, error) {
	var comments []models.Comment
	var total int64

	offset := (page - 1) * limit

	// 获取待审核评论总数
	if err := database.DB.Model(&models.Comment{}).Where("status = 0").Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	result := database.DB.Preload("Post").Preload("User").
		Where("status = 0").
		Order("created_at DESC").
		Offset(offset).Limit(limit).
		Find(&comments)

	if result.Error != nil {
		return nil, 0, result.Error
	}

	return comments, total, nil
}

// GetRecentComments 获取最近评论
func (r *CommentRepository) GetRecentComments(limit int) ([]models.Comment, error) {
	var comments []models.Comment
	result := database.DB.Preload("Post").Preload("User").
		Where("status = 1").
		Order("created_at DESC").
		Limit(limit).
		Find(&comments)
	return comments, result.Error
}